package cn.itcast.service.impl;

import cn.itcast.domain.CheckGroup;
import cn.itcast.domain.CheckItem;
import cn.itcast.entity.PageResult;
import cn.itcast.entity.QueryPageBean;
import cn.itcast.mapper.CheckGroupMapper;
import cn.itcast.service.CheckGroupService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;

@Service
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private CheckGroupMapper groupMapper;


    public PageResult getPage(QueryPageBean pageBean) {

        Integer currentPage = pageBean.getCurrentPage();
        Integer pageSize = pageBean.getPageSize();
        String queryString = pageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<CheckGroup> pages = groupMapper.findPageByCondition(queryString);
        long total = pages.getTotal();
        List<CheckGroup> rows = pages.getResult();

        return new PageResult(total,rows);
    }

    public void addGroup(CheckGroup checkGroup, Integer[] checkitemIds) {
        //添加表单项
        groupMapper.addGroup(checkGroup);
        // 添加中间表的数据
        // 找到 添加项对应的id值 ,添加到中间表
        int id = checkGroup.getId();
        for (int i = 0; i <checkitemIds.length ; i++) {
            int items = checkitemIds[i];
            groupMapper.addCombine(id,items);
        }

    }

    public List<Integer> findEditById(Integer id) {
        //根据CheckGroup 的id 找到items的id的集合
        // 根据id的集合的遍历 获得CHeckItem的List集合
        List<CheckItem> itemList = new ArrayList<CheckItem>();
        List<Integer> ids =groupMapper.selectComboByCheckGroup_Id(id);
        return ids;
    }

    public void editByParam(Integer[] checkitemIds, CheckGroup checkGroup) {
        //update checkgroup表单数据
        groupMapper.updateCheeckGroupForm(checkGroup);
        int groupId = checkGroup.getId();
        //删除中间表 关于group 的id的数据
        groupMapper.deleteComboTableById(groupId);
        //重新赋值 中间表
        for (int i = 0; i < checkitemIds.length; i++) {
            int itemId = checkitemIds[i];
            groupMapper.insertNewCombo(groupId,itemId);
        }
    }

    public void deleteGroup(Integer id) {

        //删除中间表的数据
        groupMapper.deleteComboTableById(id);

        //删除group表的数据
        groupMapper.deleteGroup(id);
    }

    public List<CheckGroup> findAll() {
        return groupMapper.findAllPage();
    }
}
